本主题假设您已经创建了一个新的Visual Studio工程,并为您的工程添加了适当的引用。
步骤1)创建标记
这是让您开工的XAML标记:
XAML |
拷贝代码
|
---|---|
<c1:C1Chart Name="c1Chart1"> <c1:C1Chart.Data> <c1:ChartData SeriesItemsSource="{Binding SeriesDataCollection}"> <c1:ChartData.SeriesItemTemplate> <DataTemplate> <c1:DataSeries Label="{Binding Year}" ValuesSource="{Binding Values}" /> </DataTemplate> </c1:ChartData.SeriesItemTemplate> </c1:ChartData> </c1:C1Chart.Data> <c1:C1ChartLegend DockPanel.Dock="Right" /> </c1:C1Chart> |
请注意,SeriesItemsSource以及SeriesItemTemplate属性在ChartData 对象上进行设置,他们将绑定到具体的值。
步骤2)创建视图模型
接下来,您需要创建您的项目视图。
右键单击您的项目名称,选择添加新项|选择代码文件,将其命名为ViewModel.cs,并单击“确定”。
将下面的代码添加到您的代码文件中,以创建视图模型:
C# |
拷贝代码
|
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; namespace ChartAutomaticSeries { public static class ViewModelData { public static int NUM_SERIES = 5; public static int NUM_POINTS = 8; public static Random Rnd = new Random(); private static ChartModelData _data; public static ChartModelData ChartData { get { if (_data == null) { _data = new ChartModelData(); } return _data; } } } public class ChartModelData { public ObservableCollection<SeriesData> SeriesDataCollection { get { if (_seriesDataCollection == null) { _seriesDataCollection = new ObservableCollection<SeriesData>(); for (int i = 0; i < ViewModelData.NUM_SERIES; i++) _seriesDataCollection.Add(new SeriesData(2010 + i)); } return _seriesDataCollection; } } private ObservableCollection<SeriesData> _seriesDataCollection; } public class SeriesData : INotifyPropertyChanged { int _year; double[] _values; public SeriesData(int year) { _year = year; _values = new double[ViewModelData.NUM_POINTS]; for (int i = 0; i < ViewModelData.NUM_POINTS; i++) _values[i] = ViewModelData.Rnd.Next(0, 100); } public int Year { get { return _year; } set { if (_year != value) { _year = value; OnPropertyChanged("Year"); } } } public double[] Values { get { return _values; } set { if (_values != value) { _values = value; OnPropertyChanged("Values"); } } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } } |
步骤3)添加代码
切换回您的MainWindow.xaml文件。右键单击“页面”,并从“上下文”菜单中选择“查看代码”。
编辑现有的代码,以便它类似于以下:
C# |
拷贝代码
|
---|---|
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new ChartModelData(); } } } |